package com.qianchang.microfinance.gpsmanager;

import android.Manifest;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationManager;
import android.net.Uri;
import android.support.v4.app.ActivityCompat;

/**
 * Created by SSC on 2017/12/22.
 */

public class LocationGPSManager {

    private Context mContext;
    private static volatile LocationGPSManager instance = null;
    private LocationManager locationManager;
    private static String mLocateType;
    private boolean isOPenGps;
    private long mMinTime;
    private float mMinDistance;
    private GPSLocation mGPSLocation;
    private static final String GPS_LOCATION_NAME = android.location.LocationManager.GPS_PROVIDER;
    private boolean isGpsEnabled;


    private LocationGPSManager(Context context) {
        this.mContext = context;
        initData(context);
    }

    public static LocationGPSManager getInstance(Context context) {
        if (instance == null) {
            synchronized (LocationGPSManager.class) {
                if (instance == null) {
                    instance = new LocationGPSManager(context);
                }
            }
        }
        return instance;
    }

    private void initData(Context context) {
        locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        //定位类型：GPS
        mLocateType = locationManager.GPS_PROVIDER;
        //默认不强制打开GPS设置面板
        isOPenGps = false;
        //默认定位时间间隔为1000ms
        mMinTime = 1000;
        //默认位置可更新的最短距离为0m
        mMinDistance = 0;
    }

    /**
     * 方法描述：设置发起定位请求的间隔时长
     *
     * @param minTime 定位间隔时长（单位ms）
     */
    public void setScanSpan(long minTime) {
        this.mMinTime = minTime;
    }

    /**
     * 方法描述：设置位置更新的最短距离
     *
     * @param minDistance 最短距离（单位m）
     */
    public void setMinDistance(float minDistance) {
        this.mMinDistance = minDistance;
    }

    public void start(GPSLocationListener gpsLocationListener) {
        this.start(gpsLocationListener, isOPenGps);
    }

    /**
     * 方法描述：开启定位
     *
     * @param gpsLocationListener
     * @param isOpenGps           当用户GPS未开启时是否强制用户开启GPS
     */
    public void start(GPSLocationListener gpsLocationListener, boolean isOpenGps) {
        this.isOPenGps = isOpenGps;
        mGPSLocation = new GPSLocation(gpsLocationListener);
        isGpsEnabled = locationManager.isProviderEnabled(GPS_LOCATION_NAME);
        if (!isGpsEnabled && isOPenGps) {
            openGPS(mContext);
        }
        if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission
                (mContext, Manifest.permission.ACCESS_COARSE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        //获取上次最后一次位置
        Location lastKnownLocation = locationManager.getLastKnownLocation(mLocateType);
        mGPSLocation.onLocationChanged(lastKnownLocation);
        //备注：参数2和3，如果参数3不为0，则以参数3为准；参数3为0，则通过时间来定时更新；两者为0，则随时刷新
        locationManager.requestLocationUpdates(mLocateType, mMinTime, mMinDistance, mGPSLocation);
    }

    /* 强制帮用户打开GPS
     * @param context
     */
    public static final void openGPS(Context context) {
        Intent GPSIntent = new Intent();
        GPSIntent.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider");
        GPSIntent.addCategory("android.intent.category.ALTERNATIVE");
        GPSIntent.setData(Uri.parse("custom:3"));
        try {
            PendingIntent.getBroadcast(context, 0, GPSIntent, 0).send();
        } catch (PendingIntent.CanceledException e) {
            e.printStackTrace();
        }
    }


    /**
     * 方法描述：终止GPS定位,该方法最好在onPause()中调用
     */
    public void stop() {
        if (mContext != null) {
            if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) !=
                    PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(mContext,
                    Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                return;
            }
            if (mGPSLocation != null) {
                locationManager.removeUpdates(mGPSLocation);
            }
        }
    }


    private boolean checkGPSIsOpen(Context mContext) {
        boolean isOpen;
        LocationManager locationManager = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);
        isOpen = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        return isOpen;
    }


}